package com.eptok.gw.szcups.cups.codec;

import java.nio.BufferUnderflowException;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ys8583.parse.IOMessage;

import com.eptok.gw.szcups.common.GateWayConstant;
import com.solab.iso8583.common.ByteUtil;



/**
 *@author:heqishan, Email:heqishan@gmail.com
 *2013-3-5 下午03:31:21
 */
public class Decoder extends CumulativeProtocolDecoder {
	
	private static final Logger log = LoggerFactory.getLogger(Decoder.class);

	private String decoderName;
	public Decoder(String decoderName){
		this.decoderName = decoderName;
	}
	
	@Override
	protected boolean doDecode(IoSession session, IoBuffer in,
			ProtocolDecoderOutput out) throws Exception {
		int start = in.position();
		try{
			if (in.hasRemaining()) {
				if (in.remaining() < 4){
					return false;
				} 
				byte[] lenByte = new byte[4];
				in.get(lenByte);
				int len = Integer.parseInt(new String(lenByte,GateWayConstant.CHAR_ENCODE));
				
				//心跳
				if(len == 0){
					return true;
				}
				
//				int len = Integer.parseInt(in.getString(4, Constant.CHARSET.newDecoder()));
				byte[] bodyByte = new byte[len];
				in.get(bodyByte);
				
				byte[] message = ByteUtil.byteAndByte(lenByte, bodyByte);
				log.debug(decoderName + "接收到完整数据:" + ByteUtil.BinaryToHexString(message));
				
				IOMessage ioMessage = new IOMessage(GateWayConstant.MSG_CODE_TEMPLATE_ID,bodyByte);
				out.write(ioMessage);
				return true;
			}
		}catch(BufferUnderflowException e){
			//do nothing
		}
		in.position(start);
		return false;
	}

}
